/**
 * bem helper
 * bem() // 'table'
 * bem('content') // 'table__content'
 * bem({ border }) // 'table table--border'
 * bem('content', { border }) // 'table__content table__content--border'
 * bem(['border', 'stripe']) // 'table table--border table--stripe'
 */

export type Modifier = any
export type Modifiers = Modifier | Modifier[]

function generate(name: string, modifiers?: Modifiers): string {
  if (!modifiers) return ''

  if (typeof modifiers === 'string') return ` ${name}--${modifiers}`

  if (Array.isArray(modifiers)) return modifiers.reduce<string>((ret, item) => ret + generate(name, item), '')

  return Object.keys(modifiers).reduce(
    (ret, key) => ret + (modifiers[key] ? generate(name, key) : ''),
    ''
  )
}

export function createBem(name: string) {
  return function (element?: Modifiers, modifiers?: Modifiers): Modifiers {
    if (element && typeof element !== 'string') {
      modifiers = element
      element = ''
    }

    element = element ? `${name}__${element}` : name

    return `${element}${generate(element, modifiers)}`
  }
}
